package com.trkj.taoruiyun;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.trkj.base.BaseFragment;
import com.trkj.base.Constants;
import com.trkj.base.OnResponseResultListener;
import com.trkj.base.User;
import com.trkj.base.newwork.ProgressBarPostDataFromRemote;
import com.trkj.base.newwork.WaitingDataFromRemote;
import com.trkj.base.utils.Base64String;
import com.trkj.base.utils.BitmapTools;
import com.trkj.base.utils.DeleteFile;
import com.trkj.base.utils.UserService;
import com.trkj.push.NotificationActivity;
import com.trkj.usercenter.DeptScoreActivity;
import com.trkj.usercenter.LoginActivity;
import com.trkj.usercenter.NoticeActivity;
import com.trkj.usercenter.ScoreActivity;
import com.trkj.usercenter.SetupActivity;
import com.trkj.usercenter.UpdatePasswordActivity;
import com.trkj.usercenter.UserDetailActivity;
import com.trkj.usercenter.about.AboutActivity;
import com.trkj.usercenter.charts.ChartActivity;
import com.trkj.usercenter.feedback.FeedbackActivity;
import com.trkj.usercenter.question.QuestionActivity;
import com.trkj.usercenter.star.StarActivity;
import com.trkj.widget.view.RoundImageViewByXfermode;
import com.trkj.widget.view.listview.ListViewUtils;

import java.io.File;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by LiZanhong on 2015/06/15.
 */
public class MyFragment extends BaseFragment implements ListView.OnItemClickListener,
        View.OnClickListener {
    private DeleteFile deleteFile;
    private Base64String base64String;
    private View root;
    private ListView listView;
    private ImageView headerImage;

    class Item {
        public String icon;
        public String title;

        public Item(String icon, String title) {
            this.icon = icon;
            this.title = title;
        }
    }

    class ItemAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(getActivity())
                    .inflate(R.layout.fragment_usercenter_item, null);

            TextView listItemIcon = (TextView) convertView.findViewById(R.id.list_item_icon);
            TextView listItemTitle = (TextView) convertView.findViewById(R.id.list_item_title);
            TextView listItemArrow = (TextView) convertView.findViewById(R.id.list_item_arrow);

            Constants.Font.setAwesomeFont(getActivity(), listItemIcon);
            Constants.Font.setAwesomeFont(getActivity(), listItemArrow);
            listItemIcon.setText(items.get(position).icon);
            listItemTitle.setText(items.get(position).title);
            listItemIcon.setTextColor(getColor(R.color.orange));
            listItemArrow.setText(Constants.ResString.getString(getActivity(), R.string.fa_angle_right));

            return convertView;
        }
    }

    private List<Item> items = new ArrayList<Item>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        base64String = new Base64String();
        deleteFile = new DeleteFile();

        items.clear();
        items.add(new Item(Constants.ResString.getString(this.getActivity(), R.string.fa_file_text_o), "我的资料"));
        items.add(new Item(Constants.ResString.getString(this.getActivity(), R.string.fa_unlock_alt), "修改密码"));
        items.add(new Item(Constants.ResString.getString(this.getActivity(), R.string.fa_bell_o), "韬睿通知"));
        items.add(new Item(Constants.ResString.getString(this.getActivity(), R.string.fa_adn), "推送消息"));
        items.add(new Item(Constants.ResString.getString(this.getActivity(), R.string.fa_question_circle), "提问&回复"));
        items.add(new Item(Constants.ResString.getString(this.getActivity(), R.string.fa_graduation_cap), "荣誉墙"));
        items.add(new Item(Constants.ResString.getString(this.getActivity(), R.string.fa_star_o), "学分记录"));
        items.add(new Item(Constants.ResString.getString(this.getActivity(), R.string.fa_line_chart), "数据统计"));
        items.add(new Item(Constants.ResString.getString(this.getActivity(), R.string.fa_area_chart), "部分学分排行榜"));
        items.add(new Item(Constants.ResString.getString(this.getActivity(), R.string.fa_cogs), "设置"));
        items.add(new Item(Constants.ResString.getString(this.getActivity(), R.string.fa_question), "意见反馈"));
        items.add(new Item(Constants.ResString.getString(this.getActivity(), R.string.fa_quote_left), "关于"));
        items.add(new Item(Constants.ResString.getString(this.getActivity(), R.string.fa_bitbucket), "清除缓存"));
        items.add(new Item(Constants.ResString.getString(this.getActivity(), R.string.fa_arrow_right), "注销"));
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (root != null) return root;

        if (listView == null) {
            root = inflater.inflate(R.layout.fragment_usercenter, container, false);
        }
        listView = (ListView) root.findViewById(R.id.list);

        ListViewUtils.setListViewHeightBasedOnChildren(listView);
        if (listView.getAdapter() == null) {
            listView.setAdapter(new ItemAdapter());
        }
        listView.setOnItemClickListener(this);
        headerImage = (ImageView) root.findViewById(R.id.header_image);
        headerImage.setOnClickListener(this);
        resetUser();
        resetHeaderImage();
        return root;
    }


    /**
     * 更新用户名
     */
    public void resetUser() {
        TextView userName = (TextView) root.findViewById(R.id.user_name);
        TextView deptName = (TextView) root.findViewById(R.id.dept_name);
        User user = UserService.getInstance(getActivity()).parseUser();
        if (user != null) {
            userName.setText(user.userName);
            deptName.setText(getActivity().getResources().getString(R.string.trkj) + "  " + user.deptName);
        }
    }

    /**
     * 更新头像
     */
    public void resetHeaderImage() {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this.getActivity());
        boolean b = sp.getBoolean("header_image_type", true);
        RoundImageViewByXfermode byXfermode = (RoundImageViewByXfermode) headerImage;

        if (b) {
            byXfermode.setType(RoundImageViewByXfermode.TYPE_CIRCLE);
        } else {
            byXfermode.setType(RoundImageViewByXfermode.TYPE_ROUND);
        }

        User user = UserService.getInstance(getActivity()).parseUser();
        if (user != null) {
            if (user.avator != null) {
                headerImage.setImageBitmap(base64String.stringToBitmap(user.avator));
                return;
            }
            headerImage.setImageResource(R.drawable.default_header);
        }
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        if (root != null) {
            //滚动面板滚动到最顶部
            final ScrollView sv = (ScrollView) root.findViewById(R.id.scroll);
            sv.post(new Runnable() {
                @Override
                public void run() {
                    sv.fullScroll(ScrollView.FOCUS_UP);
                }
            });
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = null;
        switch (position) {
            case 0:
                intent = new Intent(UserDetailActivity.ACTION);
                startActivity(intent);
                break;
            case 1:
                intent = new Intent(UpdatePasswordActivity.ACTION);
                startActivity(intent);
                break;
            case 2:
                intent = new Intent(NoticeActivity.ACTION);
                startActivity(intent);
                break;
            case 3:
                intent = new Intent(NotificationActivity.ACTION);
                startActivity(intent);
                break;
            case 4:
                intent = new Intent(QuestionActivity.ACTION);
                startActivity(intent);
                break;
            case 5:
                intent = new Intent(StarActivity.ACTION);
                startActivity(intent);
                break;
            case 6:
                intent = new Intent(ScoreActivity.ACTION);
                startActivity(intent);
                break;
            case 7:
                intent = new Intent(ChartActivity.ACTION);
                startActivity(intent);
                break;
            case 8:
                intent = new Intent(DeptScoreActivity.ACTION);
                startActivity(intent);
                break;
            case 9:
                intent = new Intent(SetupActivity.ACTION);
                startActivityForResult(intent, Constants.ActivityCode.SETUP_REQUEST_CODE);
                break;
            case 10:
                intent = new Intent(FeedbackActivity.ACTION);
                startActivity(intent);
                break;
            case 11:
                intent = new Intent(AboutActivity.ACTION);
                startActivity(intent);
                break;
            case 12:
                this.clearCache();
                break;
            case 13:
                AlertDialog.Builder builder = new AlertDialog.Builder(MyFragment.this.getActivity())
                        .setTitle("注销")
                        .setMessage("韬睿科技提醒您，确定要注销登录吗？")
                        .setNegativeButton("好的，注销", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                UserService.getInstance(MyFragment.this.getActivity()).logout();
                                //开启登陆窗口
                                Intent intent = new Intent(LoginActivity.ACTION);
                                startActivityForResult(intent, Constants.ActivityCode.LOGON_REQUEST_CODE);
                            }
                        })
                        .setNeutralButton("不了，谢谢", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
                break;
        }
    }

    /**
     * 选择头像
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MyFragment.this.getActivity())
                .setTitle("选择头像")
                .setItems(new String[]{"从相册中获取", "拍照", "删除头像", "取消"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            //从相册中获取
                            Intent i = new Intent(Intent.ACTION_PICK);
                            i.setType("image/*");
                            startActivityForResult(i, Constants.ActivityCode.PHOTO_REQUEST_CODE);
                        } else if (which == 1) {
                            //拍照
                            Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(i, Constants.ActivityCode.CAMERA_REQUEST_CODE);
                        }  else if (which == 2) {
                            //删除头像
                            showAndUpload(
                                    BitmapFactory.decodeResource(getResources(), R.drawable.default_header),
                                    false);
                        }else {
                            dialog.dismiss();
                        }
                    }
                });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.ActivityCode.LOGON_REQUEST_CODE &&
                resultCode == Activity.RESULT_OK) {
            //重新登陆后一时间用户信息（名字和头像）
            resetUser();
            resetHeaderImage();
        } else if (requestCode == Constants.ActivityCode.PHOTO_REQUEST_CODE &&
                resultCode == Activity.RESULT_OK) {
            //从相册中获取
            if (data != null) {
                Uri uri = data.getData();
                crop(uri);
            }
        } else if(requestCode == Constants.ActivityCode.PHOTO_CUT_REQUEST_CODE &&
                resultCode == Activity.RESULT_OK) {
            if (data != null) {
                Bitmap image = data.getParcelableExtra("data");
                if (image != null) {
                    showAndUpload(image, true);
                }
            }
        }else if (requestCode == Constants.ActivityCode.CAMERA_REQUEST_CODE &&
                resultCode == Activity.RESULT_OK) {
            //拍照
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                Bitmap image = bundle.getParcelable("data");
                if (image != null) {
                    showAndUpload(image, true);
                }
            }
        } else if (requestCode == Constants.ActivityCode.SETUP_REQUEST_CODE) {
            resetHeaderImage();
        }
    }

    /**
     * 显示并上传头像
     *
     * @param image
     */
    private void showAndUpload(Bitmap image, boolean isCompress) {
        Bitmap bitmap = null;
        if(isCompress){
            bitmap = BitmapTools.compress(image);
        }else{
            bitmap = image;
        }

        //显示在ImageView组件上
        headerImage.setImageBitmap(bitmap);
        //将image上传到服务器
        uploadHeaderImage(bitmap);
    }

    /**
     * 上传头像
     *
     * @param bitmap
     */
    private void uploadHeaderImage(final Bitmap bitmap) {
        ProgressBarPostDataFromRemote dataFromRemote =
                new ProgressBarPostDataFromRemote(getActivity());
        dataFromRemote.setResponseResultListener(new OnResponseResultListener() {
            @Override
            public void onResponseResult(String result) {
                if (JSON.parseObject(result).getBoolean("success")) {
                    toast("恭喜，头像已保存");

                    retainUserInfo();
                } else {
                    toast("头像上传失败");
                }
            }
        });
        String url = MessageFormat.format(Constants.ApiUrl.UPDATE_UEER_INFO,
                UserService.getInstance(getActivity()).parseUser().userId);
        String param = "avator=" + base64String.bitmapToString(bitmap);
        dataFromRemote.execute(url, param);
    }

    private void crop(Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);

        intent.putExtra("outputFormat", "JPEG");// 图片格式
        intent.putExtra("noFaceDetection", true);// 取消人脸识别

        intent.putExtra("return-data", true);

        // 开启一个带有返回值的Activity，请求码为PHOTO_CUT_REQUEST_CODE
        startActivityForResult(intent, Constants.ActivityCode.PHOTO_CUT_REQUEST_CODE);
    }

    private void retainUserInfo(){
        WaitingDataFromRemote dataFromRemote = new WaitingDataFromRemote(this.getActivity());
        dataFromRemote.setResponseResultListener(new OnResponseResultListener() {
            @Override
            public void onResponseResult(String result) {
                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject.getBoolean("success")) {
                    JSONObject user = jsonObject.getJSONObject("user");
                    UserService.getInstance(getActivity()).saveUser(user);
                }
            }
        });
        String url = MessageFormat.format(Constants.ApiUrl.GET_USER_DETAIL,
                UserService.getInstance(getActivity()).parseUser().userId);
        dataFromRemote.execute(url);
    }

    /**
     * 清除缓存
     */
    protected void clearCache() {
        File file = getActivity().getDir("webview", Context.MODE_PRIVATE);
        if (file != null) {
            deleteFile.DeleteFolder(file.getPath());
            toast("缓存清除完成");
        }
    }


}
